package sample.controller.todo;

import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.StringUtil;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;

public class UpdateController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger(UpdateController.class.getName());

    @Override
    public Navigation run() {
        String key = key();
        if (!StringUtil.isEmpty(key)) {

            DatastoreService datastoreService =
                DatastoreServiceFactory.getDatastoreService();
            
            try {
                Entity todo = datastoreService.get(KeyFactory.stringToKey(key));
                todo.setProperty("content", asString("content"));
                
                // 保存
                Transaction transaction = datastoreService.beginTransaction();
                try {
                    datastoreService.put(transaction, todo);
                    transaction.commit();
                    
                } finally {
                    if (transaction.isActive()) {
                        transaction.rollback();
                    }
                }
            } catch (EntityNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        return redirect(basePath);
    }
}
